package com.isoftstone.merchant.controller.system.user;

import com.isoftstone.bank.controller.base.BaseController;
import com.isoftstone.common.Page;

import com.isoftstone.common.Tidings;
import com.isoftstone.common.entity.SysRole;
import com.isoftstone.common.entity.SysUser;
import com.isoftstone.common.service.ISysRoleService;
import com.isoftstone.common.service.ISysUserRoleService;
import com.isoftstone.common.service.ISysUserService;


import com.isoftstone.merchant.entity.mdept.MDept;
import com.isoftstone.merchant.entity.mdept.SysUserDept;
import com.isoftstone.merchant.service.feeUser.FeeUserService;
import com.isoftstone.merchant.service.mdept.IMdeptService;
import com.isoftstone.merchant.service.mdept.ISysUserDeptService;
import com.isoftstone.merchant.service.merchant.MerchantService;
import com.isoftstone.util.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.Null;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.net.URLDecoder;
import java.util.*;

@Controller
public class SysUsercontroller extends BaseController {


    @Autowired
    ISysUserService sysUserService;

    @Autowired
    ISysUserRoleService sysUserRoleService;

    @Autowired
    IMdeptService mdeptService;

    @Autowired
    MerchantService merchantService;

    @Autowired
    ISysRoleService sysRoleService;

    @Autowired
    ISysUserDeptService sysUserDeptService;
    @Autowired
    FeeUserService feeUserService;
    /*
    *
    * 得到商户员工列表
    * */
    @RequiresPermissions("mms-menu.001.003")
    @RequestMapping("/merchant/user/getEmplistPage")
    public ModelAndView getEmplistPage(Page page) {
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/sys_management/user_manage");
        return md;
    }
    @RequestMapping("/merchant/user/getUserlistPage")
    @ResponseBody
    public Object getUserlistPage(Page page) {
        PageData pd = this.getPageData();
        Tidings< List<SysUser>> tidings = new Tidings<List<SysUser>>();
        String userId=this.getUser().getUserid();
        List<MDept>deptids=null;
        try {
            deptids=feeUserService.getalldeptByUserId(userId);//得到用户对应的deptid
            if(deptids!=null){
                List<String>list=new ArrayList<String>();
                for(MDept mDept1:deptids){
                    list.add(mDept1.getDeptId());
                }
                pd.put("deptIds",list);//看到当前用户部门的缴费用户
            }
            String keywords = pd.getString("inputVar");
            if (keywords != null) {
                String keywords1 = URLDecoder.decode(keywords, "UTF-8");
                pd.put("keywords", keywords1);
                page.setPd(pd);
            }

            if(null != pd.get("corpIds") && !"".equals( pd.get("corpIds")) ){//银行端进入
                String corpIds = pd.get("corpIds").toString();
                pd.put("corpIds",Arrays.asList(corpIds.substring(0,corpIds.length()-1)));
            }else{//商户端
                pd.put("corpId",this.getUser().getCorpId());
                pd.put("usercode",this.getUser().getUsercode());
                pd.put("type1","01");
            }
            page.setPd(pd);
            List<SysUser> empList = sysUserService.getUserlistPage(page);
            tidings.setT(empList).setPage(page);
            tidings.setStatus(Const.SUCCESS);
        } catch (Exception e) {
            tidings.setStatus(Const.ERROR);
            e.printStackTrace();
        }

        return tidings;
    }


    /*
    * 查看该登录名是否已存在
    * */
    @RequestMapping("/merchant/user/haveUser")
    @ResponseBody
    public Object haveUser(String userCode){
        Tidings<String> tidings=new Tidings<String>();
        try {
            String userCode1=sysUserService.getUserCodeByUserCode(userCode);
            if (StringUtils.isBlank(userCode1)){
                tidings.setStatus(Const.SUCCESS);
                tidings.setMsg("用户名未被注册，可以使用！");
                return tidings;
            }else {
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("用户名已被注册，请重新输入用户名！");
                return tidings;
            }
        } catch (Exception e) {
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("用户名已被注册，请重新输入用户名！");
            e.printStackTrace();
        }
        return tidings;
    }
        /*
        * 添加
        *
        * */


    @RequestMapping("/merchant/user/save")
    @ResponseBody
    public Object save(SysUser sysUser) {
        Tidings<String> tidings = new Tidings<String>();


        PageData pd =   this.getPageData();
            //String deptId= pd.getString("treeId");
       String deptId=pd.getString("treeInfo");
        if (deptId!=null){
        String[] split = deptId.split(",");
        String userid=UuidUtil.getNumFormatUUID();
        try {
            String suserId = this.getUser().getUserid();//当前登陆者员工编号
            if ("".equals(suserId) || suserId == null) {
              String  corpId = this.getUser().getCorpId();
            }
                if (split.length>0){
                    for (String s : split) {
                        if (StringUtils.isNotBlank(s)) {//更新员工机构关系
                            sysUserDeptService.updateUserDeptByUserIdAndDeptId(userid, s);
                        };
                    }
                    sysUser.setUserid(userid);//商户id
                    //sysUser.setUsercode(UuidUtil.getNumFormatUUID());//用户名
                    sysUser.setType("02");//01--超级管理员 02--管理员 03--柜员
                    sysUser.setCorpId(this.getUser().getCorpId());//商户编号
                    sysUser.setPassword( DigestUtils.md5Hex(("a747cea3c1efabd3b5f5b60a81be59b6" + "-" + sysUser.getUsercode())).toUpperCase());//密码
                    sysUser.setStatus("02");//01：未审核02：正常 03：禁用
                    sysUser.setCreateDate(new Date());//创建时间
                    sysUser.setCreator(this.getUser().getNickname());//创建人
                    sysUser.setSystem("02");//01：银行端管理系统 02：缴费单位端管理系统
                    sysUserService.saveUser(sysUser);//保存
                    if(StringUtils.isNotBlank(sysUser.getRoleid())) {
                        sysUserRoleService.updateUserRoleByUserIdAndRoleId(userid, sysUser.getRoleid());//更新用户与角色对应关系
                    }
                    tidings.setStatus(Const.SUCCESS);
                    tidings.setMsg("保存成功！");
                }else {
                    tidings.setStatus(Const.ERROR);
                    tidings.setMsg("机构不能为空！");
                    return tidings;
                }
        } catch (Exception e) {
            e.printStackTrace();
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("保存失败！");
            e.printStackTrace();
        }
        }else {
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("请选择机构！");
            return tidings;
        }
        return tidings;
    }


    @RequestMapping(value = "merchant/user/touserUpdate",method = RequestMethod.POST)
    @ResponseBody
    public Object toUserUpdate(String roleId,String userid) {
        Map map= new HashMap();
        Tidings<Map> tidings = new Tidings<Map>();
        PageData pd = this.getPageData();
     //  String deptIds= pd.getString("treeId");
        try {
            ArrayList<String> deptNamelist = new ArrayList<>();
            List<SysRole> rolelist=sysRoleService.getRolelist(this.getUser().getCorpId());
          //  List<String> deptlist=sysUserDeptService.getDeptIdByUserId(userid);//从数据库去deptId
            List<SysUserDept>  deptlist=sysUserDeptService.getDeptIdAndNameByUserId(userid);
            String corpName=merchantService.getCorpNameBycorIp(this.getUser().getCorpId());
            if(deptlist!=null){
                for (SysUserDept dept : deptlist) {
                    if(dept!= null){
                           String deptName= dept.getDeptName();
                        deptNamelist.add(deptName);
                    }

                }
            }
           /* if(deptIds!=null){
                String[] dept = deptIds.split(",");
                for (String deptId : dept) {
                    String deptName = mdeptService.getDeptNameBydeptId(deptId);
                    deptNamelist.add(deptName);
                }
            }*/
            map.put("corpName",corpName);
            map.put("deptlist",deptlist);
            map.put("deptNamelist",deptNamelist);//根据前台传入userId便利出deptId，并查出deptName存入集合
            map.put("rolelist",rolelist);
            tidings.setT(map);
            tidings.setStatus(Const.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            tidings.setStatus(Const.ERROR);
        }
        return tidings;
    }
       /*
        * 修改
        *
        * */


    @RequestMapping(value = "merchant/user/userUpdate",method = RequestMethod.POST)
    @ResponseBody
    public Object userUpdate(SysUser sysUser) {
        Tidings<String> tidings = new Tidings<String>();
        try {
            String corpId=this.getUser().getCorpId();//得到当前登陆者企业编号
            String userId=sysUser.getUserid();//得到被修改员工编号

            PageData pd =   this.getPageData();
            String deptId=pd.getString("treeInfo");
            String[] split = deptId.split(",");
//////////

            SysUser user=sysUserService.getUserById(userId); //得到被修改员工企业编号
           if(StringUtils.equals(corpId, user.getCorpId())){ //如果当前登陆者员工编号、和被修改者企业编号相同执行
                   if(split.length>0){
                       List<SysUserDept> list= sysUserDeptService.getDeptIdAndNameByUserId(userId);//得到改用户已绑定所有机构
                       if(list.size()!=0) {
                           for (SysUserDept sysUserDept : list) {//删除改员工已绑定机构
                               sysUserDeptService.deleteUserDeptBydeptId(sysUserDept.getDeptid());
                           }
                       }
                       for (String s : split) {
                           if (StringUtils.isNotBlank(s)) {
                               sysUserDeptService.updateUserDeptByUserIdAndDeptId(userId, s);
                           }
                        }
                       sysUserService.updateUser(sysUser);//修改用户信息
                           if(StringUtils.isNotBlank(sysUser.getRoleid())) {
                               sysUserRoleService.updateUserRoleByUserIdAndRoleId(userId, sysUser.getRoleid());//更新用户与角色对应关系
                           }
                       tidings.setStatus(Const.SUCCESS);
                       tidings.setMsg("修改成功！");
                       return tidings;
                   }else {
                       tidings.setStatus(Const.ERROR);
                       tidings.setMsg("请选择机构！");
                       return tidings;

                   }
               } else {
               tidings.setStatus(Const.ERROR);
               tidings.setMsg("对不起您无此操作权限！");
               return tidings;
                }
            } catch (Exception e) {
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("修改失败！");
                e.printStackTrace();
            }
            return tidings;
        }

        /*
        *
        * 跳转详情
        * */
    @RequestMapping("/merchant/user/toUserDetial")
    @ResponseBody
    public ModelAndView toUserDetail(Page page) {
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/sys_management/user_manage_details");
        return md;
    }

    @RequestMapping("/merchant/user/UserDetial")
    @ResponseBody
    public Object userDetail(String userId) {
       Tidings<SysUser> tidings=new Tidings<SysUser>();
       String corpId=this.getUser().getCorpId();
        try {
            SysUser sysUser=sysUserService.getSysUserByCorpIdAndUserId(corpId,userId);
            if(sysUser!=null){
                tidings.setT(sysUser);
                tidings.setStatus(Const.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tidings;
    }
     /*
     * 删除用户
     * */

    @RequestMapping("/system/user/deleteSysUser")
    @ResponseBody
    public Object deleteSysUser(String userid) {
        Tidings<String> tidings = new Tidings<String>();
        try {
            String scorpId=this.getUser().getCorpId();  //得到当前登录者企业编号
            SysUser sysUser=sysUserService.getUserById(userid);//被删除用户
            String CorpId=sysUser.getCorpId();//查出被删除商户编号
         if(StringUtils.equals(scorpId,CorpId)){//判断登陆者企业编号是否与员工企业编号相等
                sysUserService.getUserById(userid);
                //sysUserRoleService.deleteUserRole(userid);
                sysUserService.deleteSysUserbyUserIdandCorpId(userid,this.getUser().getCorpId());
                sysUserDeptService.deleteUserDeptByUserId(userid);//删除用户的同时，也删除部门与用户关联
                sysUserRoleService.deleteUserRole(userid);//删除用户同时，也删除用户角色联系
                tidings.setStatus(Const.SUCCESS);
                tidings.setMsg("删除成功！");
            }else {
                tidings.setStatus(Const.ERROR);
                tidings.setMsg("非本企业管理员，不可以删除！");
            }
        } catch (Exception e) {
            tidings.setStatus(Const.ERROR);
            tidings.setMsg("删除失败！");
            e.printStackTrace();
        }
        return tidings;
    }
                /*
                *  重置密码
                * */
            @RequestMapping("/system/user/updatePassword")
            @ResponseBody
            public Object resetPassWord(String userid, String nickname) {
                Tidings<String> tidings = new Tidings<String>();
                try {
                    //得到员工企业编号
                    SysUser sysUser = sysUserService.getUserById(userid);
                    String string= DigestUtils.md5Hex("a747cea3c1efabd3b5f5b60a81be59b6" + "-" + sysUser.getUsercode()).toUpperCase();
                    sysUser.setPassword(string);
                    String corpId = sysUser.getCorpId();
                    //如当前登陆者跟被修改人同一企业 择修改否择失败
                  if(StringUtils.equals(corpId,this.getUser().getCorpId()) || Const.SystemCode.CODE_BMS.equals(this.getUser().getSystem())){
                        sysUserService.updateUser(sysUser);
                        tidings.setStatus(Const.SUCCESS);
                        tidings.setMsg("密码重置成功！");
                    }else {
                        tidings.setStatus(Const.ERROR);
                        tidings.setMsg("密码重置失败！");
                    }
                } catch (Exception e) {
                    tidings.setStatus(Const.ERROR);
                    tidings.setMsg("保存失败！");
                    e.printStackTrace();
                }
                return tidings;
            }





}

